import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import StudentInfo from "@/views/StudentInfo";
import TeacherInfo from "@/views/TeacherInfo";
import LoginView from "../views/LoginView";
import user from "../api/user";
// import LoginV from "../views/LoginV";

Vue.use(VueRouter)

const routes = [

    {
        path: '/',
        name: 'home',
        component: HomeView
    },
    {
        path: '/login',
        name: 'login',
        component: LoginView
    },
    {
        path: '/about',
        name: 'about',
        // route level code-splitting
        // this generates a separate chunk (about.[hash].js) for this route
        // which is lazy-loaded when the route is visited.
        component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue'),
        children: [
            {
                path: 'student',
                name: 'student',
                component: StudentInfo
            },
            {
                path: 'teacher',
                name: 'teacher',
                component: TeacherInfo
            }
        ]
    }
]

const router = new VueRouter({
    routes
})
//对路由进行权限控制
// 全局前置守卫：初始化时、每次路由切换前执行
var hasAddDynamicRoute =  false;
router.beforeEach((async (to, from, next) => {
    let b = to.path.toString().startsWith('/login');
    if (b){
        next();
        return
    }
    let token = sessionStorage.getItem('token');
    if (!b) {
        let token = sessionStorage.getItem('token');
        let expireTime = sessionStorage.getItem('expireTime');
        let time = new Date().getTime();
        if (token == null || expireTime - time < 0) {
            next('/login')
            return
        }
    }
    if (token && !hasAddDynamicRoute){
        // 动态路由
        let response = await user.getAuthRouter();
        console.log('routers = ',response.data)
        response.data.forEach(r => {
            let newRouter = {
                name: r.name,
                path: r.path.replace('/',''),
            }
            newRouter.component = () => import( '../views/' + r.name + 'View');
            router.addRoute("about",newRouter)
            // router.options.routes[2].children.push(newRouter)
        })
        hasAddDynamicRoute = true;
        // router.addRoute("about2",{
        //     name: 'role',
        //     path: 'role',
        //     component:()=> import('./views/RoleView.vue')
        // })
        // router.addRoutes(router.options.routes);

        next({ ...to, replace: true })
        return
    }
    console.log(router)
    next()
}))

// 全局后置守卫：初始化时、每次路由切换后执行
router.afterEach(((to, from) => {
    console.log('afterEach', to, from)
}))

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch((err) => err);
};

export default router
